const Base = require('./base')
const jssdk = require('./jssdk')
module.exports = class extends Base {
  /**
     * 根据传入id实例化token
     * @param {*} id
     */
  async instance (appid) {
    this.access_token = await this.get_access_token(appid)
    return this
  }
  get ticket () {
    return jssdk(this.access_token)
  }

  apiurl (key) {
    // yy.log.debug(`https://api.weixin.qq.com/cgi-bin/${key}?access_token=${this.access_token}`)
    return `https://api.weixin.qq.com/cgi-bin/${key}?access_token=${this.access_token}`
  }
  httpGet (key) {
    return yy.http.get(this.apiurl(key))
  }
  httpPost (key, data) {
    data = data || {}
    return yy.http.post(this.apiurl(key), data)
  }
  /**
     * 发送消息模板
     * @param o
     * @returns {*}
     */
  send_template (o = {}) {
    let post = {
      touser: '',
      template_id: '',
      url: '',
      data: ''
    }
    post = Object.assign({}, post, o)
    if (!post.touser || !post.template_id) return
    return this.httpPost('message/template/send', post)
  }

  /**
     * 自定义菜单
     */
  get_custom_menu () {
    return this.httpGet('get_current_selfmenu_info')
  }

  create_custom_menu (post) {
    return this.httpPost('addconditional', post)
  }

  remove_custom_menu (post) {
    return this.httpPost('delconditional', post)
  }

  /**
     * 菜单
     * @returns {*}
     */
  get_menu () {
    return this.httpGet('menu/get')
  }

  remove_menu () {
    return this.httpGet('menu/delete')
  }

  create_menu (post = {}) {
    return this.httpPost('menu/create', post)
  }

  /**
     * 永久二维码
     * @param sceneId
     * @param action_info
     * @returns {*}
     */
  limit_qrcode (sceneId, action_info = null) {
    const data = {
      'action_name': 'QR_LIMIT_SCENE',
      'action_info': action_info || {scene: {'scene_id': sceneId}}
    }
    if (typeof sceneId === 'string') {
      data.action_name = 'QR_LIMIT_STR_SCENE'
      data.action_info.scene = {'scene_str': sceneId}
    }
    return this.httpPost('qrcode/create', data)
  }

  /**
     * 临时二维码
     * @param sceneId 场景id
     * @param expire 过期时间 秒为单位 该二维码有效时间，以秒为单位。 最大不超过604800（即7天）。
     * @param action_info 二维码内容
     */
  tmp_qrcode (sceneId, expire = 604800, action_info = null) {
    const data = {
      'expire_seconds': expire,
      'action_name': 'QR_SCENE',
      'action_info': action_info || {scene: {'scene_id': sceneId}}
    }
    return this.httpPost('qrcode/create', data)
  }

  /**
     * 显示二维码
     * @param ticket
     * @returns {*}
     */
  show_qrcode (ticket) {
    return `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${ticket}`
  }

  /**
     * 获取白名单
     * @returns {*}
     */
  get_ip () {
    return this.httpGet('getcallbackip')
  }

  /**
     * 生成短连接
     * @param url
     * @returns {*}
     */
  short_url (url) {
    return this.httpPost('shorturl', {action: 'long2short', long_url: url})
  }
}
